import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'widget_theme.dart';

class CommonAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget? leading;
  final Widget? title;
  final String? titleData;
  final List<Widget>? actions;
  final bool? centerTitle;
  final bool automaticallyImplyLeading;
  final Color? backgroundColor;
  final Color? titleColor;
  final Color? iconColor;
  final double? height;
  final SystemUiOverlayStyle? systemOverlayStyle;

  const CommonAppBar({
    Key? key,
    this.title,
    this.titleData,
    this.leading,
    this.actions,
    this.height,
    this.centerTitle,
    this.automaticallyImplyLeading = true,
    this.titleColor,
    this.iconColor,
    this.backgroundColor,
    this.systemOverlayStyle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var appBarTheme = Theme.of(context).appBarTheme;
    final backIcon = WidgetTheme.of(context)?.appbarBackIcon ??
        const Icon(Icons.chevron_left);
    final centerTitle =
        this.centerTitle ?? WidgetTheme.of(context)?.appBarCenterTitle ?? false;
    return AppBar(
      systemOverlayStyle: systemOverlayStyle,
      leading: leading ??
          (automaticallyImplyLeading
              ? appbarLeading(
                  context: context,
                  icon: backIcon,
                  color: iconColor ?? appBarTheme.iconTheme?.color)
              : null),
      title: title ??
          Text(
            titleData ?? '',
            style: titleColor != null
                ? appBarTheme.toolbarTextStyle?.copyWith(color: titleColor)
                : appBarTheme.toolbarTextStyle,
          ),
      actions: actions,
      centerTitle: centerTitle,
      automaticallyImplyLeading: automaticallyImplyLeading,
      backgroundColor: backgroundColor ?? appBarTheme.backgroundColor,
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(height ?? kToolbarHeight);
}

Widget appbarLeading({
  required BuildContext context,
  VoidCallback? onPressed,
  Widget icon = const Icon(Icons.chevron_left),
  Color? color,
}) {
  var appBarTheme = Theme.of(context).appBarTheme;
  return IconButton(
    icon: icon,
    color: color ?? Colors.black,
    iconSize: appBarTheme.iconTheme?.size ?? 16,
    onPressed: onPressed ?? () => Navigator.maybePop(context),
  );
}
